import json
import logging
import os, time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
import random
import string
import requests
import uuid
from kafka_kit import Kafka_consumer, Kafka_producer

VEHICLE_COLOR_MAP = {'1': '1', '2': '5', '3': '8', '4': '9', '5': '3', '6': '2', '7': '4', '8': '6', '9': '12',
                     '10': '10', '11': '11', '12': '14', '13': '14'}
PLATE_COLOR_MAP = {'1': '6', '2': '5', '3': '1', '4': '2', '5': '9', '6': '99', '7': '99','0':'99'}


def init_log():
    logger = logging.getLogger()
    logger.setLevel(level=logging.INFO)
    if len(logger.handlers) == 0:
        # handler = logging.FileHandler("log.txt")
        handler = logging.StreamHandler()
        handler.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
    return logger


logger = init_log()
url = ''
executor = ThreadPoolExecutor(max_workers=30)


def api(data):
    # data = {"cdh":"2","jdchphm":"苏CZ252P","tp2_dzwjmc":"http://172.20.140.23:8009/pic?did=0&bid=20763819&pid=1083074564&ptime=1590112259","gcxh":"900718201427122836","gc_rqsj":1590112254258,"jdchpzldm":"1","tp3_dzwjmc":"http://172.20.140.23:8009/pic?did=0&bid=20763819&pid=1083062280&ptime=1590112259","kkbh":"6a8e645d0e474812a22a850ea710afb0","fxlx":"0"}
    hphm = data['jdchphm']
    if 'tp3_dzwjmc' in data and data['tp3_dzwjmc'] != '':
        param = {
            "version": 2,
            "imageUrls": [
                data['tp3_dzwjmc']
            ],
            "calcParam":
                "{\"Recognize\":{\"Call\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Crash\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Color\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Similar\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Marker\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Plate\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Sunroof\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Brand\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"SpareTire\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Rack\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Type\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Convertible\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Belt\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Danger\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Slag\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Lid\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"SchoolBus\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Taxi\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Manned\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1},\"Face\":{\"Mode\":0,\"IsRec\":true,\"TopN\":1}},\"Detect\":{\"DetectRegion\":[0,0,0,0],\"IsDet\":true,\"Version\":1001,\"MaxCarWidth\":0,\"Mode\":0,\"MinCarWidth\":0,\"Threshold\":20,\"Licence\":\"" +
                hphm + "\"}}"
        }
        res = requests.post(url, json=param)
        res.encoding = 'utf-8'
        res = res.json()
        # logger.info(res)
        # res = json.loads(res, ensure_ascii=False)
        # logger.info(res['ImageResults'][0]['Vehicles'][0]['Recognize']['Plate']['Licence'])
        return res


def rannum(num):
    salt = ''
    for i in range(num):
        salt += random.choice(string.digits)
    return salt


def ranstr(num):
    salt = ''
    for i in range(num):
        salt += random.choice(string.ascii_uppercase + string.digits)
    return salt


def result_convert(data, mes):
    motor_vehicle_list = []
    for image_result in data['ImageResults']:
        for v in image_result['Vehicles']:
            vehicle = {}
            vehicle['MotorVehicleID'] = rannum(48)
            vehicle['InfoKind'] = 1
            vehicle['Direction'] = '9'
            vehicle['SourceID'] = rannum(41)
            vehicle['TollgateID'] = mes['kkbh']
            vehicle['StorageUrl1'] = mes["tp3_dzwjmc"]
            x, y, w, h = tuple(v['Detect']['Car']['Rect'])
            vehicle['LeftTopX'], vehicle['LeftTopY'], vehicle['RightBtmX'], vehicle['RightBtmY'] = x, y, x + w, y + h
            bz_tz = timezone(timedelta(hours=8))
            appear_time = datetime.strftime(datetime.fromtimestamp(mes['gc_rqsj'] / 10 ** 3, tz=bz_tz), "%Y%m%d%H%M%S")
            vehicle['AppearTime'] = appear_time
            vehicle['SafetyBelt'] = 1
            if v['Recognize']['Belt']['Code'] == 0:
                vehicle['SafetyBelt'] = int(not v['Recognize']['Belt']['MainDriver']['NoBelt'])
            if v['Recognize']['Color']['Code'] == 0:
                vehicle['VehicleColor'] = VEHICLE_COLOR_MAP[v['Recognize']['Color']['TopList'][0]['Code']]
            if v['Recognize']['Call']['Code'] == 0:
                vehicle['Calling'] = int(v['Recognize']['Call']['HasCall'])
            if v['Recognize']['Brand']['Code'] == 0:
                vehicle['VehicleBrand'] = v['Recognize']['Brand']['TopList'][0]['Name']
            if v['Recognize']['Brand']['Code'] == 0:
                vehicle['BrandReliability'] = str(v['Recognize']['Brand']['TopList'][0]['Score'])
            if v['Recognize']['Type']['Code'] == 0:
                vehicle['VehicleClass'] = v['Recognize']['Type']['TopList'][0]['Code']
            vehicle['HasPlate'] = v['Recognize']['Plate']['Code'] == 0
            vehicle['PlateColor'] = PLATE_COLOR_MAP[v['Recognize']['Plate']['Color']['Code']] if \
            v['Recognize']['Plate']['Code'] == 0 else '99'
            vehicle['PlateClass'] = str(v['Recognize']['Plate']['Type']).zfill(2) if v['Recognize']['Plate'][
                                                                                         'Code'] == 0 else '99'
            vehicle['PlateNo'] = v['Recognize']['Plate']['Licence'] if (
                        v['Recognize']['Plate']['Code'] == 0 and v['Recognize']['Plate']['Licence'] != '未识别') else '无车牌'

            # 添加subimage
            subimagelist = {"SubImageInfoObject": [
                {
                    "Type": "01",
                    "StoragePath": mes['tp3_dzwjmc'],
                    "ImageID": ranstr(41),
                    "EventSort": 17,
                    "ShotTime": appear_time,
                    # "Height": 1680,
                    "Data": "",
                    # "Width": 2048 ,
                    "FileFormat": "Other"
                }
            ]
            }
            vehicle["SubImageList"] = subimagelist

            motor_vehicle_list.append(vehicle)
            break

    result_data = {
        "MotorVehicleListObject": {
            "MotorVehicleObject": motor_vehicle_list
        }
    }

    return result_data if len(motor_vehicle_list)>0 else None


def deal_data(message):
    try:
        mes = json.loads(message.decode())
        res = api(mes)
        if res is not None:
            df = result_convert(res, mes)
            if df is not None:
                producer.send_df(df)
    except:
        logger.info(res)
        logger.exception("deal data error")


if __name__ == '__main__':
    try:
        url = os.getenv("AI_URL", "http://32.60.129.20:8082/recog/")
        bootstrap_server = os.getenv("BOOTSTRAP_SERVER", "32.60.129.7:9092")
        kafkatopic = os.getenv("TOPIC", "ehl-vehicle")
        consumer = Kafka_consumer(bootstrap_servers=bootstrap_server, kafkatopic=kafkatopic,
                                  groupid='seemo')
        sinktopic = os.getenv("SINKTOPIC", "tr")
        producer = Kafka_producer(bootstrap_servers=bootstrap_server, kafkatopic=sinktopic,
                                  is_json=True)
        data = consumer.read_df()
        logger.info("start")
        for message in data:
            executor.submit(deal_data, message)
    except:
        logger.exception("system error")
